package com.persia.tool;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.text.StrBuilder;

import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 因为很多类库都用util
 * 为避免冲突，本框架都用tool
 * @author: caibosi
 * @created: 2013-11-10
 */
public class StringTool {

    // 替换固定格式的字符串（支持正则表达式）
    public static String replaceAllWithRegex(String str, String regex, String replacement) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, replacement);
        }
        m.appendTail(sb);
        return sb.toString();
    }

    // 判断字符串是否非空
    public static boolean isNotEmpty(String str) {
        return StringUtils.isNotEmpty(str);
    }

    // 判断字符串是否为空,为null或者长度为0
    public static boolean isEmpty(String str) {
        return StringUtils.isEmpty(str);
    }

    // 若字符串为空，则取默认值
    public static String defaultIfEmpty(String str, String defaultValue) {
        return StringUtils.defaultIfEmpty(str, defaultValue);
    }

    // 是否为数字（整数或小数）
    public static boolean isNumber(String str) {
        return NumberUtils.isNumber(str);
    }

    // 是否为十进制数（整数）
    public static boolean isInteger(String str) {
        return NumberUtils.isDigits(str);
    }

    // 将驼峰风格替换为下划线风格
    public static String camelhumpToUnderline(String str) {
        Matcher matcher = Pattern.compile("[A-Z]").matcher(str);
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() + i, matcher.end() + i, "_" + matcher.group().toLowerCase());
        }
        if (builder.charAt(0) == '_') {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

    // 将下划线风格替换为驼峰风格
    public static String underlineToCamelhump(String str) {
        Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
        }
        if (Character.isUpperCase(builder.charAt(0))) {
            builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
        }
        return builder.toString();
    }

    // 分割固定格式的字符串
    public static String[] splitString(String str, String separator) {
        return StringUtils.splitByWholeSeparator(str, separator);
    }

//    // 连接集合成为字符串，复杂对象类型不能够正常toString
//    public static String join(Collection collection,char separator){
//        return StringUtils.join(collection,separator);
//    }
//
//
//    public static String join(Object[] array,char separator){
//        return StringUtils.join(array,separator);
//    }

    // 将字符串首字母大写
    public static String firstToUpper(String str) {
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }

    // 将字符串首字母小写
    public static String firstToLower(String str) {
        return Character.toLowerCase(str.charAt(0)) + str.substring(1);
    }

    /**
     * 打印对象内容
     * 支持单一对象，容器，数组（包括复杂类型）
     * @param object
     * @return
     */
    public static String toFriendlyString(Object object,String separator){
        if(object == null)
            return "";
        if(object instanceof Collection){
           if(CollectionTool.isEmpty((Collection)object))
               return "";
           return joinCollection((Collection)object,separator);

        }
        if(object.getClass().isArray()){
            Object[] array = (Object[])object;
            if(CollectionTool.isEmpty(array)){
                return "";
            }
            return joinArray(array,separator);
        }
        return ToStringBuilder.reflectionToString(object);
    }

    /**
     * 连接集合类型
     * 支持复杂对象嵌套的显示
     * @param object
     * @param separator
     * @return
     */
    private static String joinCollection(Collection object,String separator){
        Iterator iterator = object.iterator();
        // handle null, zero and one elements before building a buffer
        if (iterator == null) {
            return null;
        }
        if (!iterator.hasNext()) {
            return "";
        }
        Object first = iterator.next();
        if (!iterator.hasNext()) {
            return ToStringBuilder.reflectionToString(first);
        }

        // two or more elements
        StrBuilder buf = new StrBuilder(256); // Java default is 16, probably too small
        if (first != null) {
            buf.append(ToStringBuilder.reflectionToString(first));
        }

        while (iterator.hasNext()) {
            buf.append(separator);
            Object obj = iterator.next();
            if (obj != null) {
                buf.append(ToStringBuilder.reflectionToString(obj));
            }
        }

        return buf.toString();
    }

    /**
     * 连接数组
     * 支持复杂类型的展示
     * @param array
     * @param separator
     * @return
     */
    private static String joinArray(Object[] array,String separator){
        if (array == null) {
            return "";
        }
        int endIndex = array.length;
        int startIndex = 0;

        int bufSize = (endIndex - startIndex);
        if (bufSize <= 0) {
            return "";
        }

        bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1);
        StrBuilder buf = new StrBuilder(bufSize);

        for (int i = startIndex; i < endIndex; i++) {
            if (i > startIndex) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(ToStringBuilder.reflectionToString(array[i]));
            }
        }
        return buf.toString();
    }
}
